<?php

class DefaultController extends Controller {

    public $layout = 'application.modules.admin.views.layouts.main';

    public function actionIndex() {
        if (!Yii::app()->user->isGuest)
            $this->redirect('/admin/school/index');
        $this->render('index');
    }

    public function actionAccount() {
        $admin = new Admin();
        if (isset($_POST['User'])) {
            $admin->attributes = $_POST['User'];
            if ($admin->validate()) {
                $admin->save();
                $this->redirect('manager');
            }
        }
        $this->render('account');
    }

    /**
     * //判断用户名是否存在
      //昵称是否存在
      //email是否存在
     */
    public function actionValidate() {
        $data = array();
        $data['r'] = 1;
        $data['msg'] = '';
        if (isset($_POST['col']) && isset($_POST['colVal'])) {
            if ($_POST['col'] === 'username') {
                $username = $_POST['colVal'];
                if (User::model()->isExistUsername($username)) {
                    $data['r'] = 0;
                    $data['msg'] = '用户名已经存在';
                }
            } else if ($_POST['col'] === 'email') {
                $email = $_POST['colVal'];
                if (User::model()->isExistEmail($email)) {
                    $data['r'] = 0;
                    $data['msg'] = '邮箱已经使用';
                }
            }
        }
        $json = CJSON::encode($data);
        echo $json;
        Yii::app()->end();
    }

    public function actionLogin() {
        $admin = new AdminLoginForm();
        if (isset($_POST['username'])) {
            $admin->username = $_POST['username'];
            $admin->password = $_POST['password'];
            $admin->rememberMe = $_POST['remember'] === "true" ? true : false;
            // validate user input and redirect to the previous page if valid
            $data = array();
            if ($admin->validate() && $admin->login()) {
                $data['r'] = 1;
                $data['msg'] = 'http://link.com/admin/school/index';
            } else {
                $data['r'] = 0;
                $data['msg'] = '用户名或密码错误';
            }
            echo CJSON::encode($data);
            Yii::app()->end();
        }
        // display the login form
        $this->render('index');
    }

    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect('index');
    }

}